package com.alexgaoyh.ssoAuth.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.MutiModule.common.utils.SSOPropertiesUtilss;
import com.MutiModule.common.utils.StringUtilss;

public class AuthServlet extends HttpServlet{

	/**
	 * 登陆页面
	 */
	private static String SSOLoginPage;
	
	/**
	 * 保存的cookie名称部分
	 */
	private static String CookieName;

	/**
	 * 保存的cookie路径部分，cookie.setPath()
	 */
	private static String DomainName;
	

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		SSOLoginPage = SSOPropertiesUtilss.getSSOLoginPage();
		CookieName = SSOPropertiesUtilss.getCookieName();
		DomainName = SSOPropertiesUtilss.getDomainName();

		String username = request.getParameter("username");
		String userpassword = request.getParameter("userpassword");
		
		if (StringUtilss.isNotEmpty(username) && StringUtilss.isNotEmpty(userpassword)) {
			if (username.equals(userpassword)) {// 用户名密码相等

				String gotoURL = request.getParameter("goto");

				String sessionId = request.getSession().getId();

				Cookie cookie = new Cookie(CookieName, sessionId);

				cookie.setMaxAge(1000);

				cookie.setPath("/");

				response.addCookie(cookie);

				if (gotoURL != null) {

					response.sendRedirect(gotoURL);

				} else {

					response.sendRedirect(SSOLoginPage);

				}

			} else {

				response.sendRedirect(SSOLoginPage);

			}
		} else {
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}

	}
	
	
}
